import {appBuryingPoint, checkRiskData, fetchMenuChildShow, userInfoVerify} from "@/api/home";
import router from "@/router";
import {Toast} from "vant";
import i18n from "@/locale/index";
import {fetchUserInfo} from "@/api/my";
import {uploadFaceUpload} from '@/api/home'

const {t} = i18n.global

export function dateFormat(date, fmt = 'YYYY-mm-dd HH:MM:SS') {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        }
    }
    return fmt;
}

// 深拷贝
export function deepClone(data) {
    let result
    if (typeof data === 'object') {
        if (Array.isArray(data)) {
            result = []
            for (let i = 0; i < data.length; i++) {
                result.push(deepClone(data[i]))
            }
        } else if (data === null) {
            result = null
        } else if (data.constructor === RegExp) {
            result = data
        } else if (data.constructor === Date) {
            result = data.getTime()
        } else {
            result = {}
            for (let i in data) {
                result[i] = deepClone(data[i])
            }
        }
    } else {
        result = data
    }
    return result
}

//  防抖函数
export function debounce(fn, wait = 2000, immediate = true) {
    let timer;
    return function () {
        if (timer) clearTimeout(timer);
        if (immediate) {
            // 如果已经执行过，不再执行
            let callNow = !timer;
            timer = setTimeout(() => {
                timer = null;
            }, wait)
            if (callNow) {
                fn.apply(this, arguments)
            }
        } else {
            timer = setTimeout(() => {
                fn.apply(this, arguments)
            }, wait);
        }
    }
}

// 压缩图片

export function compressImage(file) {
    let disposeFile = file;
    if (Object.prototype.toString.call(file) === "[object Blob]") {
        disposeFile = new File([file], file.name, {type: file.type});
    }
    const read = new FileReader()
    read.readAsDataURL(disposeFile);
    return new Promise((resolve, reject) => {
        try {
            read.onload = (e) => {
                const img = new Image();//项目中尽量避免出现有两个Image构造函数
                img.src = e.target.result;
                img.onload = async function () {
                    let w = Math.floor(this.width / 2),//压缩后的图片宽度是原来的一半
                        h = Math.floor(this.height / 2);//压缩后的图片高度是原来的一半
                    const canvas = document.createElement("canvas");
                    const ctx = canvas.getContext("2d");
                    let base64;
                    canvas.setAttribute("width", w);
                    canvas.setAttribute("height", h);
                    ctx.drawImage(this, 0, 0, w, h);
                    base64 = canvas.toDataURL(disposeFile["type"], 0.7);
                    const newFile = dataURLtoFile(base64, disposeFile.name)
                    if (parseFloat(parseInt(newFile.size) / 1024 / 1024).toFixed(2) >= 2) {
                        const res = await compressImage(newFile)
                        resolve(res)
                    } else {
                        resolve(newFile);
                    }
                };
            };
        } catch (error) {
            reject(disposeFile);
        }
    });
}

// 设置资源菜单显示
export async function setResourcesShow(type) {
    // type 9 首页权限
    const res = await fetchMenuChildShow({type: type, productName: localStorage.getItem('productName')})
    if (res.code === 1) {
        const obj = {}
        res.data.forEach(i => {
            obj[i.resourcesFieldName] = i.status
        })
        return obj
    }
}

// 获取地址栏资源
export function getCaption(name) {
    let search = (window.location.search.substr(1) || window.location.hash.split("?")[1]) || '';
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = search.match(reg);
    if (r != null) return unescape(r[2]);
    return '';
}

// 格式化日期为英文
export function formatDate_EN(date) {
    if (!date) return ''
    const dateArr = new Date(date).toDateString().split(' ')
    return dateArr[1].trim() + ' ' + dateArr[2].trim() + ',' + dateArr[3]
}

/*
  parameter：
  num：格式化目标数字
  decimal：保留几位小数，默认2位
  split：千分位分隔符，默认为,
*/
export function formatMoney(num, decimal = 0, split = '.') {
    function thousandFormat(num) {
        const len = num.length
        return len <= 3 ? num : thousandFormat(num.substr(0, len - 3)) + split + num.substr(len - 3, 3)
    }

    if (isFinite(num)) { // num是数字
        if (num === 0) { // 为0
            return num.toFixed(decimal)
        } else { // 非0
            var res = ''
            var dotIndex = String(num).indexOf('.')
            if (dotIndex === -1) { // 整数
                res = thousandFormat(String(num)) + '' + '0'.repeat(decimal)
            } else { // 非整数
                // js四舍五入 Math.round()：正数时4舍5入，负数时5舍6入
                // Math.round(1.5) = 2
                // Math.round(-1.5) = -1
                // Math.round(-1.6) = -2
                // 保留decimals位小数
                const numStr = String((Math.round(num * Math.pow(10, decimal)) / Math.pow(10, decimal)).toFixed(decimal)) // 四舍五入，然后固定保留2位小数
                const decimals = numStr.slice(dotIndex, dotIndex + decimal + 1) // 截取小数位
                res = thousandFormat(numStr.slice(0, dotIndex)) + decimals
            }
            return res
        }
    } else {
        return '--'
    }
}

// dataURL 为base64数据 filename为文件
function dataURLtoFile(dataURL, filename) {
    const arr = dataURL.split(',')
    const mime = arr[0].match(/:(.*?);/)[1]
    const bstr = atob(arr[1])
    let n = bstr.length
    const u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], filename, {type: mime})
}

// 上传人脸信息
export async function uploadFaceInfo() {
    return new Promise((resolve, reject) => {
        // 获取video和canvas元素
        var video = document.createElement('video');
        var canvas = document.createElement('canvas');
        canvas.width = 500
        canvas.height = 500
        let drawTimer = null
        var ctx = canvas.getContext('2d');
        // 获取媒体流
        navigator.mediaDevices.getUserMedia({
            video: {
                facingMode: 'user'
            }
        }).then(function (stream) {
            console.log('stream', stream)
            video.srcObject = stream;
            video.play();
            draw();
        }).catch(function (err) {
            console.log(err)
            reject()
        });

        // 绘制视频流到canvas
        async function draw() {
            ctx.drawImage(video, 0, 0, 500, 500);
            const imageUrl = canvas.toDataURL("image/png")
            drawTimer = setTimeout(async () => {
                if (imageUrl.length < 50000) {
                    draw()
                } else {
                    clearTimeout(drawTimer)
                    upload(imageUrl)
                }
            }, 1000)
        }

        // 上传信息
        async function upload(imageUrl) {
            const file = dataURLtoFile(imageUrl, 'cs111.png')
            const formData = new FormData()
            formData.append('file', file)
            formData.append('type', 4)
            const res = await uploadFaceUpload(formData)
            if (res.code === 1) {
                resolve()
            } else {
                reject()
            }
        }
    })

}

// 获取权限
function getPermission() {
    return new Promise((resolve) => {
        if (window.android) {
            // 是否获取权限
            const isPermiss = window.android.checkPermission()
            if (!isPermiss) {
                resolve(false)
            } else {
                resolve(true)
            }
        } else {
            resolve(true)
        }
    })
}

//  轮询调用安卓事件
export async function getAndroidUploadResult() {
    Toast.loading({
        duration: 0,
        message: t('加载中'),
        forbidClick: true,
    })
    const riskRes = await checkRiskData()
    // 数据库不存在日数据情况 0 要上传 1 不用
    if (riskRes.code === 1) {
        if (window.android && window.android.resetDevice) {
            window.android.resetDevice(riskRes.data === 0 ? '0' : '1')
        }
        if (riskRes.data === 1) {
            Toast.clear()
            return Promise.resolve(true)
        }
    } else {
        Toast(t('Fail error code: 0x0001'))
        return Promise.resolve(false)
    }
    let timer = null
    let timerNum = 0
    return new Promise(async (resolve) => {
        const isDevice = window.android ? window.android.isAllUploadDeviceInfo() : true;
        console.log('isDevice1', isDevice)
        if (!isDevice) {
            // 调用安卓事件
            const permission = await getPermission()
            console.log('permission',permission)
            if (!permission) {
                Toast(t('Fail error code: 0x0002'))
                return Promise.resolve(false)
            }
            timer = setInterval(() => {
                const status = window.android.isAllUploadDeviceInfo()
                console.log('isDevice2', status)
                if (status) {
                    timerNum = 0
                    clearInterval(timer)
                    Toast.clear()
                    resolve(true)
                } else {
                    if (timerNum >= 60) {
                        Toast(t('Fail error code: 0x0003'))
                        timerNum = 0
                        clearInterval(timer)
                        resolve(false)
                    }
                    timerNum++
                }
            }, 1000)
        } else {
            Toast.clear()
            resolve(true)
        }
    })
}

// 上传ad埋点
export function upLoadAdjustPoint(event) {
    if (!window.android) return;
    if (window.android.trackEvent) {
        const userId = localStorage.getItem('userId')
        window.android.trackEvent(JSON.stringify({
            eventName:event.eventName,
            userId:userId,
        }))
    }
}

/**
 * 流程跳转权限处理
 * @param flag 存储用户记录信息
 */
export async function processNext(flag) {
    Toast.loading({
        message: t('加载中'),
        duration: 0,
        forbidClick: true,
    })
    const res = await userInfoVerify()
    console.log('userInfoVerify', res.data)
    if (res.code === 1) {
        let data = res.data
        // 更新用户信息
        const r = await fetchUserInfo()
        if (r.code === 1) {
            // 存储用户全部信息
            localStorage.setItem('userWriteInfo', JSON.stringify(r.data))
        }
        if (flag) {
            // 流程埋点.
            const pointKey = {
                'identityInfo': {detailed_type: 2, type: 14},
                'personalInfo': {detailed_type: 3, type: 24},
                'workInfo': {detailed_type: 4, type: 34},
                'operatorsInfo': {detailed_type: 11, type: 40},
                'contactsInfo': {detailed_type: 5, type: 39},
                'bankCardInfo': {detailed_type: 6, type: 49},
            }
            if (pointKey[flag]) {
                appBuryingPoint(pointKey[flag])
            }
            const serveData = {
                ...data,
            }
            serveData[flag] = true
            data = serveData
            localStorage.setItem('userInfoVerify', JSON.stringify(serveData))
        }
        const {
            identityInfo,
            personalInfo,
            workInfo,
            creditInfo,
            contactsInfo,
            bankCardInfo
        } = data
        Toast.clear()
        if (!personalInfo) {
            router.push({
                path: '/rORwiYkPMKBS',
            })
            return;
        }
        if (!workInfo) {
            router.push({
                path: '/CkYcQRegPw',
            })
            return;
        }
        if (!contactsInfo) {
            router.push({
                path: '/LSgdIjyrOR',
            })
            return;
        }
        // 信用记录
        if (!creditInfo) {
            router.push({
                path: '/deySOVCMPA',
            })
            return;
        }
        if (!identityInfo) {
            router.push({
                path: '/hjakhfkaghiew',
            })
            return;
        }
        if (!bankCardInfo) {
            router.push({
                path: '/nilVFYlKmK',
            })
            return;
        }
        router.push({
            path: '/kxrCNoNoUZ',
        })
    }
}
